import ProForm, {
  DrawerForm,
  ProFormCheckbox,
  ProFormDependency,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { Card, Checkbox, Col, Divider, Row } from 'antd';
import React, { useEffect, useState } from 'react';
import { useModel } from 'umi';

import ProFormMutiLangText from '@/components/ProFormMutiLangText';
import * as apiAreaFilter from '@/services/areaFilter';
import * as c from '@/services/consts';
import * as flags from '@/services/flags';
import * as api from '@/services/vpnGroup';
import { ProFormTreeSelect } from '@ant-design/pro-components';
import { EditableProTable, ProColumns } from '@ant-design/pro-table';
import { CheckboxValueType } from 'antd/es/checkbox/Group';

type FormProps = {
  visible: boolean;
  // defaultProductId: number | undefined;
  loadGroupId: string | undefined;
  current: API.VpnGroupModel | API.VpnGroupMonitorModel | undefined;
  parent?: API.VpnGroupModel | undefined;
  onCancel: () => void;
  onSubmit: (
    record: API.VpnGroupModel | API.VpnGroupMonitorModel,
  ) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const { visible, current, parent, loadGroupId, onCancel, onSubmit } = props;
  if (!visible) {
    return null;
  }

  let defaultCurrent: Partial<API.VpnGroupModel> = {
    mutiLang: false,
    type: c.VpnGroupType.Normal.value,
    memberLevel: c.MemberLevel.Trial.value,
    changeIp: 0,
    sort: 1,
    display: true,
    status: true,
    allotConfig: { perUserIpCount: 1, perIpUserCount: 1 },
  };

  if (parent) {
    defaultCurrent = {
      mutiLang: parent.mutiLang,
      flag: parent.flag,
      parentId: parent.id,
      parentName: parent.name,
      type: parent.type,
      memberLevel: parent.memberLevel,
      changeIp: 0,
      sort: 1,
      display: true,
      status: true,
      productIds: parent.productIds,
      allotConfig: { perUserIpCount: 1, perIpUserCount: 1 },
    };
  }

  if (current && !current.allotConfig) {
    current.allotConfig = { perUserIpCount: 1, perIpUserCount: 1 };
  }

  let defaultPlatformAppVerCompareData: API.AppVerComparePolicy[] =
    current && current.policy?.platformAppVerCompares
      ? current.policy?.platformAppVerCompares
      : [];

  const [
    editablePlatformAppVerCompareKeys,
    setEditablePlatformAppVerCompareKeys,
  ] = useState<React.Key[]>(() =>
    defaultPlatformAppVerCompareData.map((item) => item.id),
  );
  const [platformAppVerCompareDataSource, setPlatformAppVerCompareDataSource] =
    useState<API.AppVerComparePolicy[]>(() => defaultPlatformAppVerCompareData);
  const [checkedList, setCheckedList] = useState<any[]>(
    current?.policy?.displayAreaFilterPolicyAreaFilterIds,
  );
  const [policyAreaList, setPolicyAreaList] = useState<any[]>([]);
  // const [currentProductIds, setCurrentProductIds] = useState<number[]>(current.productIds);

  const {
    getProduct,
    getProductOptions,
    getTags,
    getVpnGroupExTrees,
    getGeoipIspOptions,
  } = useModel('useGlobalModel', (model) => ({
    getProduct: model.getProduct,
    getProductOptions: model.getProductOptions,
    getTags: model.getTags,
    getVpnGroupExTrees: model.getVpnGroupExTrees,
    getGeoipIspOptions: model.getGeoipIspOptions,
  }));

  const productOptions = getProductOptions(false);

  const getTagOptions = (productIds: number[]) => {
    let options: any[] = [];
    if (!productIds || productIds.length == 0) {
      return options;
    }

    for (let i = 0; i < productIds.length; i++) {
      let productId = productIds[i];

      let product = getProduct(productId);

      const tags = getTags(
        [c.TagType.VpnGroup.value, c.TagType.GhostVpnGroup.value],
        productId,
      );

      for (let item of tags) {
        options.push({
          label: `(${product?.name})${item.name}`,
          value: item.id,
          disabled: !item.status,
        });
      }
    }

    return options;
  };

  const loadAreaFilters = async (params: { [key: string]: any }) => {
    const result = await apiAreaFilter.all(params);

    //console.log('loadAreaFilters: ', result);

    if (result.success && result.data && result.data.length > 0) {
      let options: any[] = [];
      for (let item of result.data) {
        let product = getProduct(item.productId);
        let areas =
          item.areaGroup == c.AreaGroup.Foreign.value
            ? item.areas
            : item.areaGroup;

        options.push({
          label: `(${product?.name})${item.name} [${areas}]`,
          value: item.id,
          disabled: !item.status,
        });
      }

      // console.log(options);

      setPolicyAreaList(options);
      //return Promise.resolve(options);
    } else {
      setPolicyAreaList([]);
    }
    // return Promise.resolve([]);
  };

  const loadGroupTreeData = async (params: any) => {
    const treeData = getVpnGroupExTrees(params?.productId);

    console.log('current.id: ', current.id);

    let list = treeData.filter((item) => {
      return (
        item.refData != null &&
        !item.refData.display &&
        item.refData.id != current.id
      );
    });

    console.log(list);

    return Promise.resolve(list);
  };

  const handleFormSubmit = async (record: API.VpnGroupModel) => {
    record.id = current?.id ?? '';
    if (!record.policy) {
      record.policy = {} as API.VpnGroupPolicy;
    }
    record.policy.displayAreaFilterPolicyAreaFilterIds = checkedList;
    record.policy.platformAppVerCompares = platformAppVerCompareDataSource;

    onSubmit(record);
  };

  useEffect(() => {
    loadAreaFilters({ productIds: current?.productIds });
  }, []);

  const onCheckChange = (list: CheckboxValueType[]) => {
    // console.log(list);
    setCheckedList(list);
  };

  const loadData = async () => {
    if (loadGroupId) {
      const result = await api.get({ key: loadGroupId });
      // console.log(result);
      if (result && result.success) {
        return Promise.resolve(result.data);
      }
      return Promise.resolve(undefined);
    } else {
      return Promise.resolve(true);
    }
  };

  const platformAppVerCompareColumns: ProColumns<API.AppVerComparePolicy>[] = [
    {
      title: '平台',
      dataIndex: 'platform',
      width: 120,
      valueType: 'select',
      fieldProps: {
        options: c.PlatformOptions,
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请选择平台' }],
        };
      },
    },
    {
      title: '比较方式',
      dataIndex: 'compareMode',
      width: 120,
      valueType: 'select',
      fieldProps: {
        options: c.AdPolicyAppVerCompareOptions,
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请选择比较方式' }],
        };
      },
    },
    {
      title: '版本号',
      width: 80,
      dataIndex: 'appVer',
      valueType: 'digit',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请填写版本号比较方式' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];

  return (
    <DrawerForm<API.VpnGroupModel | API.VpnGroupMonitorModel>
      open={visible}
      title={`${current ? '编辑' : '添加'}分组`}
      autoFocusFirstInput
      width={1224}
      onFinish={handleFormSubmit}
      initialValues={current ? current : defaultCurrent}
      request={loadData}
      omitNil={false}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      <Row gutter={24}>
        <Col span={24}>
          <ProFormSelect
            mode="multiple"
            name="productIds"
            label="产品"
            options={productOptions}
            readonly={parent != null}
            rules={[{ required: true, message: '请选择产品' }]}
            fieldProps={{
              onChange(value, option) {
                console.log(value, option);
                loadAreaFilters({ productIds: value });
              },
            }}
          />

          {parent && (
            <ProFormText name="parentName" label="上级分组" readonly={true} />
          )}
        </Col>
        <Col span={12}>
          <ProFormSelect
            name="memberLevel"
            label="用户等级"
            options={c.MemberLevelOptions}
            rules={[{ required: true, message: '请选择用户等级' }]}
            readonly={parent != null || current?.parentId != null}
          />
        </Col>
        <Col span={12}>
          <ProFormSelect
            name="type"
            label="类型"
            options={c.VpnGroupTypeOptions}
            rules={[{ required: true, message: '请选择分组类型' }]}
            readonly={parent != null || current?.parentId != null}
          />
        </Col>
        <Col span={12}>
          <ProFormSelect
            name="flag"
            label="国家/地区"
            options={flags.FlagOptions}
            fieldProps={{
              showSearch: true,
              optionItemRender(item: any) {
                return (
                  <>
                    <img
                      alt=""
                      style={{
                        // background: '#f0f0f0',
                        width: '24px',
                        height: '24px',
                        marginRight: '6px',
                        marginTop: '-9px',
                        marginBottom: '-5px',
                      }}
                      src={`/images/flagoptions/${item.value}.png`}
                    />
                    {item.label}
                  </>
                );
              },
            }}
            rules={[{ required: true, message: '请选择国家/地区' }]}
          />
        </Col>
        <Col span={12}>
          <ProFormDependency name={['productIds']}>
            {({ productIds }) => {
              if (productIds && !parent) {
                const tagOptions = getTagOptions(productIds);
                return (
                  <>
                    <ProFormSelect
                      name="tags"
                      label="分组标签"
                      options={tagOptions}
                      fieldProps={{
                        mode: 'multiple',
                        allowClear: false,
                        listHeight: 448,
                      }}
                    />
                  </>
                );
              }

              return null;
            }}
          </ProFormDependency>
        </Col>
        <Col span={12}>
          <ProFormText
            name="name"
            label="名称"
            rules={[{ required: true, message: '请输入名称' }]}
            placeholder="请输入名称"
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name="code"
            label="分组代码"
            rules={[
              { required: true },
              { min: 1 },
              { max: 8 },
              {
                pattern: /^([a-zA-Z\d_]{1,8})$/,
                message:
                  '分组代码只能包含英文字母、数字和下划线，长度为1-8个字符',
              },
            ]}
            placeholder="请输入分组代码"
          />
        </Col>
      </Row>
      <Row gutter={24}>
        <ProFormDependency name={['productIds', 'mutiLang']}>
          {({ productIds, mutiLang }) => {
            //console.log('productIds: ', productIds);
            if (productIds) {
              return (
                <>
                  <Col span={12}>
                    <ProFormSwitch name="mutiLang" label="多语言" />
                  </Col>
                  {mutiLang && (
                    <Col span={12}>
                      <ProFormMutiLangText productIds={productIds} />
                    </Col>
                  )}
                </>
              );
            }

            return null;
          }}
        </ProFormDependency>
      </Row>
      <Row gutter={24}>
        <Col span={24}>
          <ProFormText
            name="subTitle"
            label="副标题"
            placeholder="请输入副标题（英文）"
          />
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <ProFormDigit
            name="userLimit"
            label="最大用户数"
            min={0}
            max={9999999}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name="maxBandwidth"
            label="最大带宽(MB)"
            min={0}
            max={9999999}
          />
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <ProFormSelect
            name="allotMode"
            label="分配方式"
            options={c.VpnGroupAllotModeOptions}
          />
        </Col>
        <ProFormDependency name={['allotMode']}>
          {({ allotMode }) => {
            if (allotMode == c.VpnGroupAllotMode.FixedIp.value) {
              return (
                <>
                  <Col span={12}>
                    <ProFormDigit
                      name={['allotConfig', 'perUserIpCount']}
                      label="每用户IP数"
                      readonly={true}
                      fieldProps={{ defaultValue: 1 }}
                      min={1}
                      max={9999}
                    />
                  </Col>
                </>
              );
            } else if (allotMode == c.VpnGroupAllotMode.FixedUser.value) {
              return (
                <>
                  <Col span={12}>
                    <ProFormDigit
                      name={['allotConfig', 'perIpUserCount']}
                      label="每IP用户数"
                      readonly={true}
                      fieldProps={{ defaultValue: 1 }}
                      min={1}
                      max={9999}
                    />
                  </Col>
                  <Col span={24}>
                    <ProFormTextArea
                      name={['allotConfig', 'fixedUsers']}
                      label="参与分配用户(多用户换行)"
                      fieldProps={{ rows: 8 }}
                    />
                  </Col>
                </>
              );
            }
            return null;
          }}
        </ProFormDependency>
      </Row>
      <Row gutter={24}>
        <Col span={6}>
          <ProFormDigit
            name="changeIp"
            label="自动切换IP间隔"
            min={0}
            max={9999}
            addonAfter="分钟"
          />
        </Col>
        <Col span={6}>
          <ProFormDigit
            name="changeIpCount"
            label="一次切换IP数量"
            min={1}
            max={9999}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit name="sort" label="分组排序" min={0} max={9999} />
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={6}>
          <ProFormSelect
            name="protocol"
            label="支持协议"
            options={c.VpnGroupProtocols}
          />
        </Col>
        <Col span={6}>
          <ProFormSelect
            name={["policy", "cheaterId"]}
            label="Cheater类型"
            options={c.CheaterTypeOptions}
          />
        </Col>
        <Col span={4}>
          <ProFormSwitch name="display" label="客户端显示" />
        </Col>
        <Col span={4}>
          <ProFormSwitch name="blacklistGroup" label="黑名单用户分组" />
        </Col>
        <Col span={4}>
          <ProFormSwitch name="status" label="分组状态" />
        </Col>
        <Col span={24}>
          <ProFormTextArea name="remark" label="备注" />
        </Col>
      </Row>
      <Card title="桥接策略" style={{ margin: 0, padding: 0 }}>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormTreeSelect
              name="preBridgeGroupIds"
              label="桥接前置分组"
              placeholder="请选择前置分组"
              allowClear={false}
              request={loadGroupTreeData}
              // tree-select args
              fieldProps={{
                showArrow: true,
                showSearch: true,
                treeCheckable: true,
                maxTagCount: 1,
                multiple: true,
                treeDefaultExpandAll: true,
                listHeight: 600,
                treeNodeLabelProp: 'title',
                filterTreeNode: (input, option) =>
                  option && option.title
                    ? option.title
                        .toString()
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    : false,
              }}
            />
          </Col>
        </Row>
      </Card>
      <Card title="显示策略" style={{ marginTop: 20, padding: 0 }}>
        <Row gutter={24}>
          {/* <Col span={24}>
            <Divider
              orientation="left"
              orientationMargin="0"
              style={{ marginTop: 0 }}
            >
              平台渠道策略
            </Divider>
          </Col> */}
          <Col span={12}>
            <ProFormCheckbox.Group
              name={['policy', 'displayPlatforms']}
              label="平台"
              options={c.PlatformOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormCheckbox.Group
              name={['policy', 'displayChannels']}
              label="渠道"
              options={c.Channels}
            />
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              版本策略
            </Divider>
          </Col>
          {/* <Col span={12}>
            <ProFormSelect
              name={['policy', 'displayAppVerComparePolicy']}
              label="版本比较"
              options={c.GroupDisplayAppVerCompareOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormDigit
              name={['policy', 'displayAppVerComparePolicyAppVer']}
              label="版本号"
              min={0}
            />
          </Col> */}
          <Col span={24}>
            <ProForm.Item name={['policy', 'platformAppVerCompares']} label="">
              <EditableProTable<API.AppVerComparePolicy>
                rowKey="id"
                locale={{ emptyText: '暂无数据' }}
                toolBarRender={false}
                columns={platformAppVerCompareColumns}
                defaultValue={platformAppVerCompareDataSource}
                // onChange={setPlatformAppVerCompareDataSource}
                onChange={(value: API.AppVerComparePolicy[]) => {
                  setPlatformAppVerCompareDataSource(value);
                }}
                recordCreatorProps={{
                  newRecordType: 'dataSource',
                  position: 'bottom',
                  record: () => ({
                    id: `${Date.now()}`,
                    appVer: 0,
                  }),
                }}
                editable={{
                  type: 'multiple',
                  editableKeys: editablePlatformAppVerCompareKeys,
                  actionRender: (row, config, defaultDom) => [
                    //defaultDom.save,
                    defaultDom.delete,
                  ],
                  onValuesChange: (record, recordList) => {
                    setPlatformAppVerCompareDataSource(recordList);
                  },
                  onChange: setEditablePlatformAppVerCompareKeys,
                }}
                request={async () => ({
                  data: platformAppVerCompareDataSource,
                  success: true,
                })}
                // params={{ d: platformAppVerCompareDataSource }}
              />
            </ProForm.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              地区策略
            </Divider>
          </Col>
          {/* <Col span={12}>
            <ProFormDependency name={['productIds']}>
              {({ productIds }) => {
                return (
                  <ProFormCheckbox.Group
                    name={['policy', 'displayAreaFilterPolicyAreaFilterIds']}
                    label="地区"
                    params={{ productIds }}
                    request={loadAreaFilters}
                  />
                );
              }}
            </ProFormDependency>
          </Col>
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'displayAreaFilterPolicy']}
              label="策略"
              options={c.GroupDisplayAreaFilterPolicyOptions}
            />
          </Col> */}
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'displayAreaFilterPolicy']}
              label="策略"
              options={c.GroupDisplayAreaFilterPolicyOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormDependency name={['productIds']}>
              {({ productIds }) => {
                // console.log(productIds);
                return (
                  <Checkbox.Group
                    key="cgAreas"
                    value={checkedList}
                    onChange={onCheckChange}
                    style={{ marginBottom: 30 }}
                  >
                    <Row>
                      <Col span={24}>地区</Col>
                      {policyAreaList.map((val) => {
                        return (
                          <Col span={12}>
                            <Checkbox
                              key="cbAreas"
                              value={val.value}
                              disabled={val.disabled}
                            >
                              {val.label}
                            </Checkbox>
                          </Col>
                        );
                      })}
                    </Row>
                  </Checkbox.Group>
                );
              }}
            </ProFormDependency>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              新老用户策略
            </Divider>
          </Col>
          <Col span={12}>
            <ProFormDigit
              name={['policy', 'displayUserRegistDay']}
              label="注册天数"
              min={0}
              max={9999}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'displayUserRegistPolicy']}
              label="注册天数策略(符合条件用户可见)"
              allowClear={true}
              options={c.GroupDisplayUserRegistCompareOptions}
            />
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              ISP运营商策略
            </Divider>
          </Col>
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'ispFilterPolicy']}
              label="ISP运营商过滤策略"
              allowClear={true}
              options={c.IspFilterPolicyOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'ispFilterPolicyIspList']}
              label="ISP运营商分组列表"
              allowClear={true}
              mode="multiple"
              fieldProps={{
                maxTagCount: 1,
                listHeight: 600,
              }}
              options={getGeoipIspOptions()}
            />
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'displayUserPolicy']}
              label="指定用户策略"
              options={c.GroupDisplayUserPolicyOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormTextArea
              name={['policy', 'displayUsers']}
              label="Token/DeviceId(多用户换行)"
              fieldProps={{ rows: 8 }}
            />
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormSwitch
              name={['policy', 'testGroupUser']}
              label="测试组用户可见（产品配置:测试组用户）"
            />
          </Col>
        </Row>
      </Card>
    </DrawerForm>
  );
};

export default Form;
